/**
 * Created by baiguiren on 1/23/17.
 */

let async = require('async');

// The `retry` function can be used as a stand-alone control flow by passing
// a callback, as shown below:

let count = 1;
let apiMethod = function (callback) {
  //console.log(count++);
  //console.log('apiMethod');
  if (count <= 3) {
    callback('Not finish yet! ', count);
  }
};

// try calling apiMethod 3 times
async.retry(3, apiMethod, function (err, result) {
  // do something with the result
  console.log('err =', err);
  console.log('result =', result);
});

// try calling apiMethod 3 times, waiting 200ms between each retry
async.retry({times: 3, interval: 200}, apiMethod, function (err, result) {
  // do something with the result
  console.log(result);
});

// try calling apiMethod 10 times with exponential backoff
// (i.e. intervals of 100, 200, 400, ...milliseconds)
async.retry({
  times: 10,
  interval: function (retryCount) {
    return 50 * Math.pow(2, retryCount);
  }
}, apiMethod, function (err, result) {
  // do something with the result
});

// try calling apiMethod the default 5 times no delay between each retry
async.retry(apiMethod, function (err, result) {
  // do something with the result
});

// try calling apiMethod only when error condition satisfies, all other
// errors will abort the retry control flow and return to final callback
async.retry({
  errorFilter: function (err) {
    return err.message === 'Temporary error'; // only retry on a specific error
  }
}, apiMethod, function (err, result) {
  // do something with the result
});

// It can also be embedded within other control flow functions to retry
// individual methods that are not as reliable, like this:
async.auto({
  users: api.getUsers.bind(api),
  payments: async.retry(3, api.getPayments.bind(api))
}, function (err, results) {
  // do something with the results
});